package com.yy.QSManage.api;

import cn.hutool.json.JSONArray;
import com.yy.QSManage.common.Result;
import com.yy.QSManage.exception.ServiceException;
import com.yy.QSManage.model.dto.GenCodeDto;
import com.yy.QSManage.model.entity.FaSysGen;
import com.yy.QSManage.service.FaSysGenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/FaSysGenApi")
@Api(tags = "代码生成")
public class FaSysGenApi extends BaseApi<FaSysGen>{

    @Autowired
    FaSysGenService genService;

    @Value("${spring.profiles.active}")
    private String env;

    @ApiOperation("生成代码")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "path")
    @GetMapping("/genCode/{id}")
    public Result<Boolean> genCode(@PathVariable String id){
        if(env.equals("prod")){
            throw new ServiceException("生产环境已默认关闭生成代码功能！");
        }
        genService.generateCode(id);
        return Result.success();
    }

    @ApiOperation("生成代码")
    @ApiImplicitParam(name = "query", value = "query", required = true, dataType = "GenCodeDto", paramType = "body")
    @PostMapping("/genCode")
    public Result<String> genCode(@RequestBody GenCodeDto genCodeDto){
        if(env.equals("prod")){
            throw new ServiceException("生产环境已默认关闭生成代码功能！");
        }
        String codeJsonStr = genCodeDto.getCodeJsonStr();
        JSONArray jsonArray = new JSONArray(codeJsonStr);
        List<HashMap> list = jsonArray.toList(HashMap.class);
        List<HashMap<String, String>> codeJsonList = new ArrayList<>();
        for (HashMap hashMap : list) {
            codeJsonList.add(hashMap);
        }
        genService.generateCode(codeJsonList, genCodeDto);
        // 标记代码生成
        genService.updateById(FaSysGen::getIfGen, 1, genCodeDto.getGenId());
        return Result.success();
    }

    @ApiOperation("生成代码预览")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "path")
    @GetMapping("/genCodePreview/{id}")
    public Result<String> genCodePreview(@PathVariable String id){
        return Result.success(genService.generateCodePreview(id));
    }
}
